import random

from django.shortcuts import render
from django.utils.decorators import method_decorator
from django_redis import get_redis_connection
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView,ListAPIView,DestroyAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from django.core.cache import cache
from QQLoginTool import QQtool
from django.conf import settings
from itsdangerous import URLSafeSerializer
from rest_framework_jwt.settings import api_settings
from django.views.decorators.cache import cache_page
from rest_framework_jwt.views import ObtainJSONWebToken

from . import serializers
from .models import User, OAuthQQUser, Area, Address
from .serializers import QQAuthUserSerializer, UserDetailSerializer, EmailSerializer, AddressSerializer
from .tasks import send_sms_code
from ..goods.merge_cart import merge_cart_function
from ..goods.models import SKU


# 1.用户名检测
class UsernameCountView(APIView):
    def get(self,request,username):
        count = User.objects.filter(username=username).count()
        return Response({
            "count": count
        })


# 2.手机号检测
class MobileCountView(APIView):
    def get(self,reqeust,mobile):
        count = User.objects.filter(mobile=mobile).count()
        return Response({
            "count": count
        })

# 3.发送验证码
class SMSCodeView(APIView):
    def get(self,request,mobile):
        #查看是否已经发送过
        flag = cache.get("sms_flag_%s" % mobile)
        if flag:
            return Response({"message":"请求过于频繁"},status=400)
        # 存储随机码
        sms_code = random.randint(0,9999)
        print("短信验证码：%s"%sms_code)
        cache.set("sms_code_%s" % mobile,sms_code,3000)
        cache.set("sms_flag_%s"% mobile,1 ,1)
        # celery的异步发送
        send_sms_code.delay(sms_code)
        return Response({'message':'ok'})


# 4.用户注册
class UserView(CreateAPIView):
    # create完成了post的方法和数据保存的那一套动作
    serializer_class = serializers.UserSerializer


# 5. 用户登录使用jwt中的登录功能
# 需要合并购物车，需要重写下登录接口
class UserLoginView(ObtainJSONWebToken):
    def post(self, request, *args, **kwargs):
        # 调用父类原有的登录业务逻辑完成用户判断
        response = super().post(request, *args, **kwargs)

        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            # 获取user
            user = serializer.object.get('user') or request.user
            # 合并购物车
            response = merge_cart_function(request, response, user)
            return response

        return response


# 6.qq登录跳转路径获取
class QQAuthURLView(APIView):
    def get(self,request):
        state = request.query_params.get("state")
        if not  state:
            state="/"
        oauth = QQtool.OAuthQQ(client_id=settings.QQ_CLIENT_ID,client_secret=settings.QQ_CLIENT_SECRET,
                               redirect_uri=settings.QQ_REDIRECT_URI,state=state)
        login_url = oauth.get_qq_url()
        return Response({"login_url":login_url})


# 7.get用户请求后台qq用户后台是否已经绑定，post进行绑定
class QQAuthUserView(CreateAPIView):
    serializer_class = QQAuthUserSerializer
    def get(self,request): # noqa
        code = request.query_params.get("code")
        if not code:
            return Response({"error":"缺少code值"},status=400)

        oauth = QQtool.OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                               redirect_uri=settings.QQ_REDIRECT_URI, state='/')
        access_token = oauth.get_access_token(code)
        openid = oauth.get_open_id(access_token)
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except :
            # 加密open_id
            qq_u = URLSafeSerializer(settings.SECRET_KEY, "qq")
            openid_token = qq_u.dumps({'openid': openid})
            return Response({'access_token': openid_token})
        else:
            user = qq_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response =  Response({
                "token": token,
                "user_id": user.id,
                "username":user.username
            })
            response = merge_cart_function(request,user,response)
            return response

    # 重写合并购物车
    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)
        # 合并购物车
        response = merge_cart_function(request, self.user, response)
        return response


# 8.个人中心
class UserDetailView(RetrieveAPIView):
    # 校验token，拿id查用户返回数据，我们使用retrieve帮我们实现了什么？我希望我们记单词的时候也是框架先出来
    serializer_class = UserDetailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


# 9.发送校验邮箱
class EmailView(UpdateAPIView):
    serializer_class = EmailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


# 10.用户点击链接回调接口
class EmailVerifyView(APIView):
    def get(self,request):
        token = request.query_params.get("token")
        secret_email = URLSafeSerializer(settings.SECRET_KEY, "email")
        if not token:
            return Response({"errno":"缺少token"},status=400)
        try:
            data = secret_email.loads(token)
        except:
            return Response({"errno": "无效token"}, status=400)
        username = data.get("username")
        user = User.objects.get(username=username)
        user.email_active = True
        user.save()
        return Response({"message":"ok"})


# 1.获取省级消息
class AreasView(APIView):
    @method_decorator(cache_page(60))
    def get(self,request):
        areas = Area.objects.filter(parent=None)
        data = [i.to_dict() for i in areas]
        return Response(data)


# 2.获取市区县消息
class AreaView(APIView):
    @method_decorator(cache_page(60))
    def get(self,request,pk):
        areas = Area.objects.filter(parent_id = pk)
        data = [i.to_dict() for i in areas]
        return Response(data)


# 3.增删改查数据
class AddressView(ListAPIView,CreateAPIView,UpdateAPIView,DestroyAPIView):

    serializer_class = AddressSerializer

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def list(self, request, *args, **kwargs):
        # 用户列表重写
        data = self.get_queryset()
        ser = self.get_serializer(data,many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 10,
            'addresses': ser.data,
        })

    def destroy(self, request, *args, **kwargs):
        address = self.get_object()
        address.is_deleted = True
        address.save()
        return Response({"message":"ok"})


class AddressTitleView(APIView):
    def put(self,request,pk):
        title = request.data.get("title")
        address = Address.objects.get(id=pk)
        address.title = title
        address.save()
        return Response({'message':"ok"})


class AddressDefaultView(APIView):
    def put(self,request,pk):
        address = Address.objects.get(id=pk)
        user = request.user
        user.default_address = address
        user.save()
        return Response({'message':"ok"})


# 用户浏览商品记录视图
class GoodHistoryView(APIView):
    permission_classes = [IsAuthenticated]
    def get(self,request):
        user_id = request.user.id
        conn = get_redis_connection('history')
        # 根据id查询商品对象
        sku_ids = conn.lrange('history_%s' % user_id, 0, 4)
        skus = SKU.objects.filter(id__in=sku_ids)
        histories = [sku.to_dict() for sku in skus]
        return Response(histories)

    def post(self,request):
        sku_id = request.data.get("sku_id")
        user_id = request.user.id

        try:
            SKU.objects.get(id=sku_id)
        except:
            return Response({"message": "不存在商品"},status=400)

        # 简单的一个用一用cache，复杂的redis操作需要使用get_connection_redis
        redis_client = get_redis_connection("history")
        # 删除列表中有的相同的元素
        redis_client.lrem("history_%s"%user_id,0,sku_id)
        redis_client.lpush("history_%s"%user_id,sku_id)
        redis_client.ltrim("history_%s"%user_id,0,4)
        return Response({"message": "ok"})